package com.movisol.messenger.helper;

import java.io.InputStream;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Handler;
import android.util.Log;

import com.movisol.messengercommunicator.data.Contact;

public class MessengerHelper {
	
	private final static String USER = "User";
	private final static String EMAIL_KEY = "email";
	private final static String TEST_URL = "http://m.google.com";
	
	//Restrict the instantiation of the class
	private MessengerHelper()
	{}
	
	public static String getSavedEmail(Context context) {
		String email = null;

		SharedPreferences settings = context.getSharedPreferences(USER, Context.MODE_PRIVATE);
		email = settings.getString(EMAIL_KEY, null);

		return email;
	}

	public static void saveEmail(Context context, String email) {

		SharedPreferences settings = context.getSharedPreferences(USER, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();

		editor.putString(EMAIL_KEY, email);

		editor.commit();

	}
	
	public static Bitmap downloadBitmap(String url) {
	    final HttpClient client = new DefaultHttpClient();
	    final HttpGet getRequest = new HttpGet(url);

		try {
			HttpResponse response = client.execute(getRequest);
			final int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
				return null;
			}

			final HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream inputStream = null;
				try {
					inputStream = entity.getContent();
					final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
					return bitmap;
				} finally {
					if (inputStream != null) {
						inputStream.close();
					}
					entity.consumeContent();
				}
			}
		} catch (Exception e) {
			// Could provide a more explicit error message for IOException or
			// IllegalStateException
			getRequest.abort();
			Log.w("ImageDownloader", "Error while retrieving bitmap from " + url + ": " + e.toString());
		} finally {
			// if (client != null) {
			// client.close();
			// }
		}
	    return null;
	}
	
	public static void isNetworkAvailable(final Handler handler, final int timeout) {

        // ask for message '0' (not connected) or '1' (connected) on 'handler'
        // the answer must be send before before within the 'timeout' (in milliseconds)

        new Thread() {

            private boolean responded = false;

            @Override
            public void run() {

                // set 'responded' to TRUE if is able to connect with google mobile (responds fast)

                new Thread() {

                    @Override
                    public void run() {
                        HttpGet requestForTest = new HttpGet(TEST_URL);
                        try {
                            new DefaultHttpClient().execute(requestForTest); // can last...
                            responded = true;
                        } catch (Exception e) {}
                    }

                }.start();

                try {
                    int waited = 0;
                    while(!responded && (waited < timeout)) {
                        sleep(100);
                        if(!responded ) { 
                            waited += 100;
                        }
                    }
                } 
                catch(InterruptedException e) {} // do nothing 
                finally { 
                    if (!responded) { handler.sendEmptyMessage(0); } 
                    else { handler.sendEmptyMessage(1); }
                }

            }

        }.start();

	}

	public static String getNameById(List<Contact> friendList, String contactId) {
		for(Contact contact : friendList)
		{
			if(contact.getContactId().equals(contactId))
					return contact.getCalculatedName();
		}
		return "";
	}

	public static int parseColor(String string) {

		StringTokenizer st = new StringTokenizer(string, "|");
		return Color.argb(Integer.valueOf(st.nextElement().toString()), Integer.valueOf(st.nextElement().toString()),
				Integer.valueOf(st.nextElement().toString()), Integer.valueOf(st.nextElement().toString()));

	}

}
